import { PrismaClient } from '@prisma/client';

// 创建全局 Prisma 实例
const globalForPrisma = globalThis as unknown as {
  prisma: PrismaClient | undefined;
};

export const prisma = globalForPrisma.prisma ?? new PrismaClient();

if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma;

// 为兼容性导出 db 变量
export const db = prisma;

// 添加 dbOperation 函数
export async function dbOperation<T>(operation: () => Promise<T>) {
  try {
    const result = await operation();
    return { success: true, data: result, error: null };
  } catch (error: any) {
    console.error('数据库操作失败:', error);
    return { success: false, data: null, error: error.message };
  }
}


export default prisma;
